package com.zmn.oms.api.controller.third.daowei;

import com.alibaba.fastjson.JSON;
import com.zmn.common.constant.StatusConsts;
import com.zmn.oms.common.enums.ChannelFacade;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.third.core.tracker.FacadeTracker;
import com.zmn.oms.third.daowei.dto.*;
import com.zmn.oms.third.daowei.service.DaoweiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2020/02/21 15:43
 */
@RestController
@RequestMapping("/third/daowei")
@Slf4j
public class DaoweiController {
    @Autowired
    private DaoweiService daoweiService;

    /**
     * 新单
     * @param createOrderReq
     * @return
     */
    @RequestMapping("/createOrder")
    @ResponseBody
    public BaseRsp createOrder(CreateOrderReq createOrderReq) {
        String requestData = JSON.toJSONString(createOrderReq);
        log.info("【到位】收到新单消息！ Body:[{}]", requestData);

        FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                .dataIn(ChannelFacade.DAOWEI)
                .remark("收到新单消息")
                .reqSummary(requestData);

        try {
            validateCreateOrderParams(createOrderReq);

            CreateOrderRsp rsp = daoweiService.createOrder(createOrderReq);

            tracker.orderId(rsp.getOrderId())
                    .respSummary(JSON.toJSONString(rsp))
                    .success("ok".equals(rsp.getStatus()))
                    .commit();

            return rsp;
        } catch (OmsBaseException oe) {
            log.error(oe.getMessage(), oe);
            tracker.error(oe, oe.getMessage());
            return renderJson("error", oe.getMessage());
        } catch (Exception e) {
            log.error("到位创建新单系统报错：{}", e);
            tracker.error(e, e.getMessage());
            return renderJson("error", "系统错误");//系统内部错误
        }
    }

    /**
     * 校验新单数据
     * @param createOrderReq
     * @throws OmsBaseException
     */
    private void validateCreateOrderParams(CreateOrderReq createOrderReq) throws OmsBaseException {
        if (StringUtils.isBlank(createOrderReq.getAppkey())) {
            throw new OmsBaseException(StatusConsts.ERROR_PARAMS, "参数错误");
        }
        if (StringUtils.isBlank(createOrderReq.getItems())) {
            throw new OmsBaseException(StatusConsts.ERROR_PARAMS, "产品信息为空");
        }
        if (StringUtils.isBlank(createOrderReq.getPhone())) {
            throw new OmsBaseException(StatusConsts.ERROR_PARAMS, "用户电话为空");
        }
    }

    /**
     * 支付
     * @param orderPay
     * @return
     */
    @RequestMapping("/payOrder")
    @ResponseBody
    public BaseRsp payOrder(OrderPay orderPay) {
        String requestData = JSON.toJSONString(orderPay);
        log.info("【到位】收到支付消息！ Body:[{}]", requestData);

        FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                .dataIn(ChannelFacade.DAOWEI)
                .reqSummary(requestData)
                .remark("收到支付消息");

        if (StringUtils.isBlank(orderPay.getAppkey())) {
            return renderJson("error", "参数错误");//传入参数错误
        }
        BaseRsp baseRsp = daoweiService.prepayOrder(orderPay);

        tracker.respSummary(JSON.toJSONString(baseRsp))
                .success("ok".equals(baseRsp.getStatus()))
                .commit();
        return baseRsp;
    }

    /**
     * 二次支付
     * @param secondOrderPay
     * @return
     */
    @RequestMapping("/secondPayOrder")
    @ResponseBody
    public BaseRsp secondPayOrder(SecondOrderPay secondOrderPay) {
        String requestData = JSON.toJSONString(secondOrderPay);
        log.info("【到位】收到二次支付消息！ Body:[{}]", requestData);

        FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                .dataIn(ChannelFacade.DAOWEI)
                .reqSummary(requestData)
                .remark("收到二次支付消息");

        if (StringUtils.isBlank(secondOrderPay.getAppkey())) {
            return renderJson("error", "参数错误");//传入参数错误
        }
        BaseRsp baseRsp = daoweiService.secondPayOrder(secondOrderPay);

        tracker.respSummary(JSON.toJSONString(baseRsp))
                .success("ok".equals(baseRsp.getStatus()))
                .commit();
        return baseRsp;
    }

    /**
     * 取消订单
     * @param cancelOrderReq
     * @return
     */
    @RequestMapping("/cancelOrder")
    @ResponseBody
    public CancelOrderRsp cancelOrder(CancelOrderReq cancelOrderReq) {
        String requestData = JSON.toJSONString(cancelOrderReq);
        log.info("【到位】收到取消订单消息！ Body:[{}]", requestData);

        FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                .dataIn(ChannelFacade.DAOWEI)
                .reqSummary(requestData)
                .remark("收到取消订单消息");

        CancelOrderRsp rsp = null;
        if (StringUtils.isBlank(cancelOrderReq.getAppkey())) {
            rsp = new CancelOrderRsp();
            rsp.setMsg("参数错误");
            rsp.setStatus("error");
        }
        else {
            cancelOrderReq.setFromChannel(true);
            rsp = daoweiService.cancelOrder(cancelOrderReq);
        }

        tracker.respSummary(JSON.toJSONString(rsp))
                .success("ok".equals(rsp.getStatus()))
                .commit();
        return rsp;
    }

    /**
     * 取消订单
     * @param cancelOrderReq
     * @return
     */
    @RequestMapping("/cancelOrderByZmn")
    @ResponseBody
    public CancelOrderRsp cancelOrderByZmn(CancelOrderReq cancelOrderReq) {
        String requestData = JSON.toJSONString(cancelOrderReq);
        log.info("【到位】收到取消订单消息！ Body:[{}]", requestData);

        CancelOrderRsp rsp = new CancelOrderRsp();
        rsp.setStatus("error");

        if (!"zmnTest666666".equals(cancelOrderReq.getAppkey())) {
            rsp.setMsg("Who are you???");
            return rsp;
        }
        if (cancelOrderReq.getOrderId() == null) {
            rsp.setMsg("订单号不存在");
            return rsp;
        }

        cancelOrderReq.setFromChannel(false);
        CancelOrderRsp baseRsp = daoweiService.cancelOrder(cancelOrderReq);

        return baseRsp;
    }

    /**
     * 申请退款
     * @param cancelOrderReq
     * @return
     */
    @RequestMapping("/applyRefund")
    @ResponseBody
    public CancelOrderRsp applyRefund(CancelOrderReq cancelOrderReq) {
        String requestData = JSON.toJSONString(cancelOrderReq);
        log.info("【到位】收到申请退款消息！ Body:[{}]", requestData);

        FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                .dataIn(ChannelFacade.DAOWEI)
                .reqSummary(requestData)
                .remark("收到申请退款消息");

        CancelOrderRsp cancelOrderRsp = null;
        if (StringUtils.isBlank(cancelOrderReq.getAppkey())) {
            cancelOrderRsp = new CancelOrderRsp();
            cancelOrderRsp.setMsg("参数错误");
            cancelOrderRsp.setStatus("error");
        }
        else {
            cancelOrderRsp = daoweiService.applyRefund(cancelOrderReq);
        }

        tracker.respSummary(JSON.toJSONString(cancelOrderRsp))
                .success("ok".equals(cancelOrderRsp.getStatus()))
                .commit();
        return cancelOrderRsp;
    }


    /**
     * 评价
     * @param commentReq
     * @return
     */
    @RequestMapping("/comment")
    @ResponseBody
    public BaseRsp comment(CommentReq commentReq) {
        String requestData = JSON.toJSONString(commentReq);
        log.info("【到位】收到评价消息！ Body:[{}]", requestData);

        FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                .dataIn(ChannelFacade.DAOWEI)
                .reqSummary(requestData)
                .remark("收到评价消息");

        if (StringUtils.isBlank(commentReq.getAppkey())) {
            return renderJson("error", "参数错误");//传入参数错误
        }

        BaseRsp baseRsp = daoweiService.comment(commentReq);

        tracker.respSummary(JSON.toJSONString(baseRsp))
                .success("ok".equals(baseRsp.getStatus()))
                .commit();
        return baseRsp;
    }


    /**
     * 查询服务时间
     * @param serviceTimeReq
     * @return
     */
    @RequestMapping("/queryServiceTime")
    @ResponseBody
    public BaseRsp queryServiceTime(ServiceTimeReq serviceTimeReq) {
        String params = JSON.toJSONString(serviceTimeReq);
        log.info("【到位】收到查询服务时间！ Body:[{}]", params);

        FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                .dataIn(ChannelFacade.DAOWEI)
                .reqSummary(params)
                .remark("查询服务时间");

        if (StringUtils.isBlank(serviceTimeReq.getAppkey())) {
            return renderJson("error", "参数错误");//传入参数错误
        }

        ServiceTimeRsp serviceTimeRsp = daoweiService.queryServiceTime(serviceTimeReq);
        tracker.respSummary(JSON.toJSONString(serviceTimeRsp))
                .success("ok".equals(serviceTimeRsp.getStatus()))
                .commit();

        return serviceTimeRsp;
    }

    // 构建返回结果
    private BaseRsp renderJson(String status, String msg){
        BaseRsp result = new BaseRsp();
        result.setStatus(status);
        result.setMsg(msg);

        FacadeTracker.getTracker()
                .respSummary(JSON.toJSONString(result))
                .success(!"error".equals(status))
                .commit();
        return result;
    }

}
